package com.leetcode.problems015;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Date 2021/11/20 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    public List<List<Integer>> threeSum(int[] nums) {
        List<Integer> list = new ArrayList<>();
        for (int num : nums) {
            list.add(num);
        }
        Collections.sort(list);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if(i >= 1 && list.get(i).intValue() == list.get(i - 1).intValue()){
                continue;
            }
            int target = list.get(i);
            //寻找 a + b = -target
            int l = i + 1;
            int r = list.size() - 1;
            while (l < r){
                int tmp = list.get(l) + list.get(r);
                if(tmp == -target){
                    List<Integer> ans = new ArrayList<>();
                    ans.add(list.get(i));
                    ans.add(list.get(l));
                    ans.add(list.get(r));
                    res.add(ans);
                    int l1 = l;
                    int r1 = r;
                    l = l + 1;
                    r = r - 1;
                    while(l < r && list.get(l).intValue() == list.get(l1).intValue()){
                        l++;
                    }
                    while(r > l  && list.get(r).intValue() == list.get(r1).intValue()){
                        r--;
                    }

                }else if (tmp < -target){
                    l++;
                    while(l < r && list.get(l).intValue() == list.get(l - 1).intValue()){
                        l++;
                    }
                }else if (tmp > -target){
                    r--;
                    while(r > l  && list.get(r).intValue() == list.get(r + 1).intValue()){
                        r--;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] strs = {-1,0,1,2,-1,-4};
        int[] strs1 = {-2,0,0,2,2};
        System.out.println(new Solution().threeSum(strs));
        System.out.println(new Solution().threeSum(strs1));

    }
}
